# import matplotlib.pyplot as plt
import pandas as pd
import requests
from bs4 import BeautifulSoup

from matplotlib import pyplot as plt


# def get_data(url):
#     pass
#     """数据获取"""
#     resp = requests.get(url)
#     # print(resp.text)    # 文本形式的网页源代码
#     # print(resp.content.decode('gbk'))   # 二进制网页源代码
#     html = resp.content.decode('gbk')
#     soup = BeautifulSoup(html, 'html.parser')
#     tr_list = soup.find_all('tr')
#     dates, conditions, temp = [], [], []
#     for data in tr_list[1:]:
#         sub_data = data.text.split()
#         # print(sub_data)
#         dates.append(sub_data[0])
#         conditions.append(''.join(sub_data[1:3]))       # ''.join() 列表中的文字拼接成一个字符串
#         temp.append(''.join(sub_data[3:6]))
#
#     _data = pd.DataFrame()
#     _data['日期'] = dates
#     _data['天气状况'] = conditions
#     _data['气温'] = temp
#
#     return _data
#
#
# data_1_month = get_data('http://www.tianqihoubao.com/lishi/luxian/month/202201.html')
# data_2_month = get_data('http://www.tianqihoubao.com/lishi/luxian/month/202202.html')
# data_3_month = get_data('http://www.tianqihoubao.com/lishi/luxian/month/202203.html')
#
# data = pd.concat([data_1_month, data_2_month, data_3_month]).reset_index(drop=True)     # 表拼接 索引重新赋值
# print(data)
# data.to_csv('luxian.csv', index=False, encoding='utf-8')


# 二，数据可视化
# 解决中文问题
plt.rcParams['font.sans-serif'] = ['SimHei']
# 解决符号显示问题
plt.rcParams['axes.unicode_minus'] = False

df = pd.read_csv('luxian.csv')  # 读数据
# print(df.isnull().sum())            # isnull() 检查是否有空值
# print(df.head())    # 打印前五行

# 数据处理
df['最高气温'] = df['气温'].str.split('/', expand=True)[1]    # 获取做高气温
df['最低气温'] = df['气温'].str.split('/', expand=True)[0]    # 获取最低气温

df['最高气温'] = df['最高气温'].map(lambda x : int(x.replace('℃', '')))
df['最低气温'] = df['最低气温'].map(lambda x : int(x.replace('℃', '')))

dates = df['日期']
highs = df['最高气温']
lows = df['最低气温']


# 画图
fig = plt.figure(dpi=128, figsize=(10,3))     # 创建一个画图

plt.plot(dates, highs, c='red', alpha = 0.5)    # 最高温度线
plt.plot(dates, lows, c='blue', alpha = 0.5)    # 最低温度线

plt.fill_between(dates, highs, lows, facecolor = 'blue', alpha = 0.2)   #

# 图表格式
plt.title('泸县天气', fontsize = 24)
plt.xlabel('', fontsize = 6)
fig.autofmt_xdate()     # 绘制倾斜的日期标签，以免重叠
plt.ylabel('气温', fontsize = 12)
plt.tick_params(axis='both', which = 'major', labelsize = 10)

# 修改刻度
plt.xticks(dates[::20])

# 显示
plt.show()

'https://www.bilibili.com/video/BV1R34y1h7jx/?spm_id_from=333.337.search-card.all.click&vd_source=7ab93aedbd4fd6aa37bb3b82b7a50ec4'




